# -*- coding: utf-8 -*-
"""
用户设置管理模块
"""
import json
import os
from typing import Dict, Any
from config import APP_NAME
from .path_manager import get_user_settings_file, get_app_data_dir

class UserSettings:
    """用户设置管理器"""
    
    def __init__(self):
        self.settings_file = get_user_settings_file()
        self.settings = self._load_settings()
    
    def _load_settings(self) -> Dict[str, Any]:
        """加载用户设置"""
        try:
            if os.path.exists(self.settings_file):
                with open(self.settings_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            else:
                return self._get_default_settings()
        except Exception as e:
            print(f"加载用户设置失败: {e}")
            return self._get_default_settings()
    
    def _get_default_settings(self) -> Dict[str, Any]:
        """获取默认设置"""
        return {
            'export_path': os.path.join(os.path.expanduser("~"), "Desktop"),
            'export_format': 'Word',
            'auto_filename': True
        }
    
    def _save_settings(self):
        """保存用户设置"""
        try:
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump(self.settings, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存用户设置失败: {e}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取设置值"""
        return self.settings.get(key, default)
    
    def set(self, key: str, value: Any):
        """设置值并保存"""
        self.settings[key] = value
        self._save_settings()
    
    def get_export_path(self) -> str:
        """获取导出路径"""
        return self.get('export_path', os.path.join(os.path.expanduser("~"), "Desktop"))
    
    def set_export_path(self, path: str):
        """设置导出路径"""
        self.set('export_path', path)
    
    def get_export_format(self) -> str:
        """获取导出格式"""
        return self.get('export_format', 'Word')
    
    def set_export_format(self, format_name: str):
        """设置导出格式"""
        self.set('export_format', format_name)
    
    def get_auto_filename(self) -> bool:
        """获取自动生成文件名设置"""
        return self.get('auto_filename', True)
    
    def set_auto_filename(self, enabled: bool):
        """设置自动生成文件名"""
        self.set('auto_filename', enabled)
    

# 创建全局用户设置实例
user_settings = UserSettings()
